package com.wx.oauth.controller;

import static com.wx.oauth.constants.WXConstants.*;

import com.alibaba.fastjson.JSONObject;
import com.wx.oauth.utils.SignUtil;
import com.wx.oauth.utils.WXUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Chenhaowen
 * @since 2019/8/5 20:15.
 */
@Controller
@RequestMapping("/oauth/")
public class OauthController extends BaseController {


    @RequestMapping(value = "handler")
    @ResponseBody
    public void handler(){
        PrintWriter pw = null;
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            pw.print(echostr);
        }
        pw.close();
        pw = null;
    }


    @RequestMapping("main")
    @ResponseBody
    public String main(String code) {
        return "欢迎来到主页！";
    }


    @RequestMapping("auth")
    public String auth() {
        String code = request.getParameter("code");
        String openid = "";
        String redirectUrl = request.getParameter("redirect");

        try {
            String res = WXUtils.getOpenid(APPID, APPSECRET, code);
            LOGGER.info("openId from wx res:" + res);
            JSONObject json = JSONObject.parseObject(res);
            openid = json.getString("openid");
            String token = json.getString("access_token");
            if (!StringUtils.isEmpty(openid)) {
                //用户登录

                //用户信息存储到cookie
                Cookie userCookie = new Cookie(COOKIE_KEY, openid);
                //设置为“0”或负值时，关闭浏览器才会清除cookie
                userCookie.setMaxAge(-1);
                userCookie.setPath("/");
                response.addCookie(userCookie);

            }
        } catch (Exception e) {
            LOGGER.error("程序错误", e);
            return "web/common/error";
        }
        if (StringUtils.isEmpty(redirectUrl)) {
            //redirect 地址为空的话默认跳转到主页
            redirectUrl = "/wow/main";
        }
        return "redirect:" + redirectUrl;
    }


}
